package com.zhenwgang.listen_books.repository;

import com.zhenwgang.listen_books.data_object.UserDO;
import com.zhenwgang.listen_books.util.DBUtil;
import lombok.SneakyThrows;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * 用户数据库操作
 * @author Violet
 * @date 2022/07/07 09:48
 **/
public class UserRepo {
    @SneakyThrows
    public void insert(UserDO userDO){
        String sql = "insert into users (username, password) values (?, ?)";
        try (Connection c = DBUtil.connection()){
            try (PreparedStatement ps = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)){

                ps.setString(1, userDO.getUsername());
                ps.setString(2, userDO.getPassword());

                ps.executeUpdate();
                try (ResultSet rs =  ps.getGeneratedKeys()){
                    rs.next();
                    userDO.uid = rs.getInt(1);
                }
            }
        }
    }

    @SneakyThrows
    public UserDO selectOneByUserName(String username){
        String sql = "select uid, username, password from users where username = ?";
        try (Connection c = DBUtil.connection()){
            try (PreparedStatement ps = c.prepareStatement(sql)){
                ps.setString(1, username);
                try (ResultSet rs = ps.executeQuery()){
                    if (!rs.next()){
                        return null;
                    }

                    return new UserDO(
                            rs.getInt("uid"),
                            rs.getString("username"),
                            rs.getString("password")
                    );
                }
            }
        }
    }
}